# coding: utf-8
class UserController < ApplicationController

	# GET: 首页
	def index
		render :template => 'user/index.html.erb'
	end

	# GET: 注册
	def reg
		@user = User.new
	    render :template => 'user/reg2.html.erb'

	    # s = hasName? nil
	    # render :text => s
	end

	# 登陆
	def login
		if request.get?

			# 如果用户已登录，则默认跳转到文档首页
			if(session[:user] != nil)
				redirect_to :action => 'index', :controller =>'doc'
			end

			@user = User.new
		else
			@user = User.new(params[:user])
			login_user = User.find_by_name_and_pass(@user.name, formatpass(@user.pass))
			if(login_user != nil)
				cookies[:login_name] = { :value => @user.name, :expires => 1.month.from_now }
				session[:user] = login_user # 将 user 写入session
				redirect_to '/doc/'
			else
				redirect_to action: 'login', notice: 'login_failure'
			end
		end
	end

	# 提交注册信息
	def create

		@user = User.new(params[:user])
		if(@user != nil)

			# 用户名检测
			if(@user.name.length < 4)
				flash[:err] = '用户名输入有误'
				render :action => :reg, :template => 'user/reg2.html.erb'
				return; 
			end

			if(hasName? @user.name)
				flash[:err] = "用户名 #{@user.name} 已被别人注册，请换用其他名称"
				render :action => :reg, :template => 'user/reg2.html.erb'
				return
			end

			# 密码检测
			if(@user.pass.length < 6)
				flash[:err] = '登录密码太过简单'
				render :action => :reg, :template => 'user/reg2.html.erb'
				return; 
			end

			# 电子邮件检测
			unless validEmail? @user.email
				flash[:err] = '电子邮箱输入有误'
				render :action => :reg, :template => 'user/reg2.html.erb'
				return; 
			end

			# 手机号码检测
			unless validMobile? @user.mobile
				flash[:err] = '手机号码输入有误'
				render :action => :reg, :template => 'user/reg2.html.erb'
				return
			end

			# 验证码
			unless simple_captcha_valid?
				flash[:err] = '验证码输入有误'
				render :action => :reg, :template => 'user/reg2.html.erb'
				return
			end

		end

		# 注册成功
		begin
			inputpass = @user.pass # 保存原始密码用于发送注册邮件
			@user.pass = formatpass(inputpass) # 格式化密码
			if @user.save
				initDocCategory # 初始化文档类别
		  		sendRegEmail(@user, inputpass) # 发送注册邮件
		  		flash['reg_name'] = @user.name
		  		redirect_to action: "login", notice: 'reg_successfully'
			end
		rescue Exception => e
			puts e
			flash[:err] = '发生未知异常，请重新尝试'
			render :action => :reg, :template => 'user/reg2.html.erb'
		end
	end

	# 退出登录
	def logout
		session[:user] = nil
		redirect_to action: 'login', notice: 'logout'
	end


	# 个人资料显示页
	def profile
		return unless unlogin
	  	@user = session[:user]
	end

	# 个人资料提交页
	def profile_post
		return unless unlogin
		sessionUser = session[:user]
		inputUser = params[:user]

		# 验证旧密码
		if(sessionUser['pass'] != formatpass(inputUser['pass']))
			redirect_to action: 'profile', notice: 'pass_error'
			return
		end

		# 验证新密码
		pass1 = inputUser['pass1']
		if(pass1 == nil || pass1.size < 6)
			redirect_to action: 'profile', notice: 'newpass_error'
			return
		end

		# 保存新密码
		newUser = User.find(sessionUser.id)
		newUser.pass = formatpass(pass1)
		if(newUser.save)
			session[:user] = newUser
			redirect_to action: 'profile', notice: 'save_success'
		else
			redirect_to action: 'profile', notice: 'save_failure'
		end
	end

	# GET: 邮箱认证链接
	def validemail
		_success = false
		uid = params[:uid]
		email = params[:email]
		user = User.find(uid)
		if(user != nil)
			@name = user.name
			token_true = UserBll.getEmailValidCode(uid, email)
			if(token_true == params[:token])
				user['email'] = email
				user['certcode'] = UserBll.getEmailCertcode(user.certcode)
				_success = user.save
			end
		end
		@success = _success
		@page_title = '邮箱认证_天天笔记'
	end

	# GET: 忘记密码
	def forgetpass

		@page_title = '找回密码_天天笔记'

		# 下一步
		name = params[:name]
		if(name != nil)
			uid = 0
			question = ''
			email = ''
			users = User.find_by_name(name)
			if(users != nil)
				user = users
				uid = user.id
				if(user.question != nil and user.question.length > 1 and user.answer != nil and user.answer.length > 1)
					question = user.question
				end
				email = UserBll.formatEmail(user.email) if(2 & user.certcode == 2)
			end
			render :text => "{ \"userid\":#{uid}, \"question\":\"#{question}\", \"email\":\"#{email}\" }"
		end
	end

	# GET: 重置密码
	def resetpass
		@page_title = '重置密码_天天笔记'
		@success = false
		uid = params[:uid]
		token = params[:token]
		if(uid != nil and token != nil)
			user = User.find(uid.to_i)
			if(user != nil)
				sysToken = UserBll.getResetPassCode(user.id, user.created_at)
				if(sysToken == token)
					@success = true # 验证成功
					@name = user.name
				end
			end
		end
	end

	# POST: 重置密码
	def resetpass_post
		@success = 0
		begin
			uid = params[:uid]
			token = params[:token]
			pass = params[:pass]
			if(uid != nil and token != nil and pass != nil)
				user = User.find(uid.to_i)
				if(user != nil)
					sysToken = UserBll.getResetPassCode(user.id, user.created_at)
					if(sysToken == token)
						newpass = formatpass(pass) # 入库密码
						user.update_column('pass', newpass)
						@success = 1 # 验证成功
					end
				end
			end
		rescue
			puts "error:#{$!} at:#{$@}"
		end
		render :text => "{ \"state\":\"#{@success}\" }"
	end

	# POST: 检查密码问题是否正确
	# 如果正确，则返回重置密码的url地址
	def check_pass_answer
		success = 0
		token = ''
		begin
			uid = params[:uid]
			answer = params[:answer]
			user = User.find(uid.to_i)
			if(user != nil)
				if(user.question != nil and user.answer != nil)
					if(user.answer.length > 1 and user.answer == answer)
						token = UserBll.getResetPassCode(user.id, user.created_at)
						success = 1 # 验证成功
					end
				end
			end
		rescue Exception => e
			puts e
		end
		render :text => "{ \"state\":\"#{success}\", \"token\":\"#{token}\" }"
	end

	# POST: 重新设置密码的邮件发送
	def resetpass_email
		success = 0
		begin
			uid = params[:uid]
			if(uid != nil)
				user = User.find(uid.to_i)
				if(user != nil)
					if(user.email != nil and 2 & user.certcode == 2)
						# 发送邮件
						url = UserBll.getResetPassUrl(user.id, user.created_at)
						p '------- url -----'
						p url
						UserMailer.resetpass(user.email, user.name, url).deliver
						success = 1
					end
				end
			end
		rescue Exception => e
			puts e
		end
		render :text => "{ \"state\":\"#{success}\" }"
	end

	# GET: 后台.用户列表
	def admin_userlist
		return unless checkAdmin
    	@userlist = User.select('id, name, email, mobile, certcode, created_at').paginate(:page => params[:page], :per_page => 10).order("created_at desc")
    	render :template => 'admin/userlist.html.erb'
	end

private

	def unlogin
	    # 未登录状态
	    if(session[:user] == nil)
	      redirect_to :action => 'login', :controller =>'user'
	      return false
	    end
	    true
	end

	# 格式化密码
	def formatpass(pass)
		v1 = Digest::MD5.hexdigest(pass)
		v2 = v1.reverse
		v2[8, 16]
	end

	# 初始化文档类别
	def initDocCategory
		DocCategory.new( :userid => @user.id, :name => '默认类别', :sortid=> 0).save
		DocCategory.new( :userid => @user.id, :name => '学习资料', :sortid=> 1).save
		DocCategory.new( :userid => @user.id, :name => '工作文档', :sortid=> 2).save
		DocCategory.new( :userid => @user.id, :name => '生活资讯', :sortid=> 3).save
	end

	# 发送注册邮件
	def sendRegEmail(user, inputpass)
		begin
			email = user.email
			if(email != nil and (email.include? '@'))
				UserMailer.reg(user.email, user.id, user.name, inputpass).deliver
		    end
		rescue Exception => e
			puts e
		end
	end

	## 验证邮箱格式
	def validEmail?(email, allowNull = false)
		return true if(allowNull && (email == nil || email == ''))
		return false if(email == nil)
		return false if(email.length < 5)
		return false if(email.include?('@') == false)
		return false if(email.include?('.') == false)
		true
	end

	## 验证手机格式
	def validMobile?(mobile, allowNull = true)
		return true if(allowNull && (mobile == nil || mobile == ''))
		return false if(mobile == nil || mobile.length != 11)
		return mobile.match(/^1[0-9]{10}$/) != nil
	end

	# 检测用户名是否被占用
	# true 代表被占用，false 代表未被占用
	def hasName?(name)
		result = false
		begin
			result = User.find_by_name(name) != nil
		rescue Exception => e
			puts e
		end
		result
	end

end
